import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/viewmodels/auth_viewmodel.dart';
import '../../../core/utils/error_handler_extension.dart';
import '../../../shared/widgets/cached_avatar.dart';

/// 编辑个人信息页面
class EditProfilePage extends StatefulWidget {
  const EditProfilePage({super.key});

  @override
  State<EditProfilePage> createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  late TextEditingController _nicknameController;
  late TextEditingController _phoneController;
  late TextEditingController _emailController;
  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    final viewModel = context.read<AuthViewModel>();
    final user = viewModel.currentUser;
    
    _nicknameController = TextEditingController(text: user?.nickname ?? user?.username ?? '');
    _phoneController = TextEditingController(text: user?.phone ?? '');
    _emailController = TextEditingController(text: user?.email ?? '');
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  Future<void> _handleSave() async {
    if (_nicknameController.text.trim().isEmpty) {
      context.showError('昵称不能为空');
      return;
    }

    setState(() {
      _isSaving = true;
    });

    final viewModel = context.read<AuthViewModel>();
    final success = await viewModel.updateUserProfile(
      name: _nicknameController.text.trim(),
      phone: _phoneController.text.trim().isEmpty ? null : _phoneController.text.trim(),
    );

    setState(() {
      _isSaving = false;
    });

    if (!mounted) return;

    if (success) {
      context.showSuccess('保存成功');
      Navigator.of(context).pop(true);
    } else {
      context.showError(viewModel.errorMessage ?? '保存失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: const Text(
          '编辑资料',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        elevation: 0,
        actions: [
          if (_isSaving)
            const Padding(
              padding: EdgeInsets.all(16.0),
              child: SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF5B8DEF)),
                ),
              ),
            )
          else
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: TextButton(
                onPressed: _handleSave,
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                ),
                child: const Text(
                  '保存',
                  style: TextStyle(
                    color: Color(0xFF5B8DEF),
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
        ],
      ),
      body: Consumer<AuthViewModel>(
        builder: (context, viewModel, child) {
          final user = viewModel.currentUser;
          
          return SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
            child: Column(
              children: [
                // 头像区域
                Container(
                  padding: const EdgeInsets.symmetric(vertical: 32),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.04),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Container(
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: const Color(0xFF5B8DEF).withOpacity(0.2),
                                width: 3,
                              ),
                            ),
                            child: CachedAvatar(
                              imageUrl: user?.avatar,
                              name: user?.username ?? 'U',
                              size: 96,
                              borderRadius: 48,
                            ),
                          ),
                          Positioned(
                            bottom: -2,
                            right: -2,
                            child: Material(
                              color: const Color(0xFF5B8DEF),
                              shape: const CircleBorder(),
                              elevation: 4,
                              child: InkWell(
                                onTap: () {
                                  // TODO: 实现头像上传
                                  context.showInfo('头像上传功能开发中');
                                },
                                borderRadius: BorderRadius.circular(20),
                                child: Container(
                                  width: 32,
                                  height: 32,
                                  decoration: const BoxDecoration(
                                    shape: BoxShape.circle,
                                  ),
                                  child: const Icon(
                                    Icons.camera_alt,
                                    size: 16,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 20),
                      TextButton.icon(
                        onPressed: () {
                          // TODO: 实现头像上传
                          context.showInfo('头像上传功能开发中');
                        },
                        icon: const Icon(
                          Icons.edit_outlined,
                          size: 16,
                          color: Color(0xFF5B8DEF),
                        ),
                        label: const Text(
                          '更换头像',
                          style: TextStyle(
                            color: Color(0xFF5B8DEF),
                            fontSize: 15,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                            side: BorderSide(
                              color: const Color(0xFF5B8DEF).withOpacity(0.3),
                              width: 1,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                
                const SizedBox(height: 20),
                
                // 个人信息表单
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.04),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      _buildTextField(
                        label: '昵称',
                        controller: _nicknameController,
                        icon: Icons.person_outline,
                        hint: '请输入昵称',
                        required: true,
                      ),
                      Divider(height: 1, indent: 72, endIndent: 16),
                      _buildTextField(
                        label: '手机号',
                        controller: _phoneController,
                        icon: Icons.phone_outlined,
                        hint: '请输入手机号',
                        keyboardType: TextInputType.phone,
                      ),
                      Divider(height: 1, indent: 72, endIndent: 16),
                      _buildTextField(
                        label: '邮箱',
                        controller: _emailController,
                        icon: Icons.email_outlined,
                        hint: '请输入邮箱',
                        keyboardType: TextInputType.emailAddress,
                        enabled: false, // 邮箱暂时不支持修改
                      ),
                    ],
                  ),
                ),
                
                const SizedBox(height: 16),
                
                // 提示信息
                Container(
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: const Color(0xFFF0F4FF),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: const Color(0xFF5B8DEF).withOpacity(0.2),
                      width: 1,
                    ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Icon(
                        Icons.info_outline,
                        size: 18,
                        color: const Color(0xFF5B8DEF),
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Text(
                          '邮箱暂不支持修改，如需修改请联系管理员',
                          style: TextStyle(
                            fontSize: 13,
                            color: const Color(0xFF5B8DEF).withOpacity(0.9),
                            height: 1.4,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTextField({
    required String label,
    required TextEditingController controller,
    required IconData icon,
    String? hint,
    TextInputType? keyboardType,
    bool enabled = true,
    bool required = false,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  const Color(0xFF5B8DEF).withOpacity(0.15),
                  const Color(0xFF5B8DEF).withOpacity(0.08),
                ],
              ),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Icon(
              icon,
              color: const Color(0xFF5B8DEF),
              size: 22,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      label,
                      style: TextStyle(
                        fontSize: 13,
                        color: const Color(0xFF6B7280),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    if (required) ...[
                      const SizedBox(width: 4),
                      const Text(
                        '*',
                        style: TextStyle(
                          color: Color(0xFFEF4444),
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ],
                ),
                const SizedBox(height: 8),
                TextField(
                  controller: controller,
                  enabled: enabled,
                  keyboardType: keyboardType,
                  decoration: InputDecoration(
                    hintText: hint,
                    hintStyle: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 15,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                    isDense: true,
                  ),
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: enabled ? const Color(0xFF1A1A1A) : Colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

